package com.yx.backstage.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.backstage.model.UserMessage;
import com.yx.backstage.model.param.UserMessageParam;
import com.yx.backstage.model.vo.UserMessageVo;
import com.yx.backstage.service.UserMessageService;
import com.yx.backstage.config.global.BizException;
import com.yx.backstage.config.global.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

import static com.yx.backstage.converter.UserMessageConverter.handlerPageResult;

/**
 * @author YangXiong
 */
@Component
public class UserManager {
    @Resource
    private UserMessageService userMessageService;

    public CommonResult<List<UserMessageVo>> getPage(UserMessageParam param) {
        LambdaQueryWrapper<UserMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(param.getUserName()), UserMessage::getUserName, param.getUserName());
        queryWrapper.like(StringUtils.isNotEmpty(param.getPhone()), UserMessage::getPhone, param.getPhone());
        queryWrapper.like(StringUtils.isNotEmpty(param.getHobby()), UserMessage::getHobby, param.getHobby());
        queryWrapper.like(StringUtils.isNotEmpty(param.getEmail()), UserMessage::getEmail, param.getEmail());
        Page<UserMessage> userMessagePage = new Page<>(param.getCurrentPage(), param.getTotalPage());
        Page<UserMessage> page = userMessageService.page(userMessagePage, queryWrapper);
        List<UserMessageVo> result = handlerPageResult(page.getRecords());
        return CommonResult.success(result, page.getTotal());
    }

    public Boolean updateStatus(UserMessageParam param) {
        UserMessage userMessage = userMessageService.getById(param.getId());
        if (Objects.isNull(userMessage)){
            throw new BizException("非法操作，用户不存在");
        }
        UpdateWrapper<UserMessage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", param.getId());
        updateWrapper.set("enable", param.getEnable());
        return userMessageService.update(updateWrapper);
    }

    public Boolean deleteUser(UserMessageParam param) {
        if(Objects.isNull(param.getId())){
            throw new BizException("参数不能为空");
        }
        UserMessage message = userMessageService.getById(param.getId());
        if(Objects.isNull(message)){
            throw new BizException("非法操作，用户不存在");
        }
        return userMessageService.removeById(param.getId());
    }
}
